import { PrismaClient } from "@prisma/client";
import { NextRequest, NextResponse } from "next/server";

interface NoteRequest {
  userId: string;
  title: string;
  avatar: string;
  content: string;
  date: string;
  images: string[];
  status: string;
  giteeUrl: string;
}

const prisma = new PrismaClient();
export async function DELETE(request: NextRequest) {
  try {
    // 解析请求中的id
    const url = request.nextUrl;
    const id = url.searchParams.get("id") as string;

    // 查找与这个id关联的笔记
    const note = await prisma.note.findUnique({
      where: {
        id,
      },
    });

    // 如果笔记不存在，返回错误
    if (!note) {
      return NextResponse.json({ message: "日志不存在" }, { status: 404 });
    }

    // 删除这个笔记
    await prisma.note.delete({
      where: {
        id,
      },
    });

    // 返回成功响应
    return NextResponse.json({ message: "该日志已删除" }, { status: 200 });
  } catch (error) {
    // 处理可能出现的错误
    console.error("Error deleting note:" + error);

    // 对于其他错误，返回内部错误消息
    return NextResponse.json({ message: "日志删除异常" }, { status: 500 });
  } finally {
    // 确保在请求结束后关闭PrismaClient
    prisma.$disconnect();
  }
}
export async function GET(req: NextRequest, res: NextResponse) {
  try {
    // 获取查询参数或者从请求体(req.body)中解析出userId，具体取决于你的需求
    const url = req.nextUrl;
    const userId = url.searchParams.get("userId") as string;

    // 查询数据库
    const notes = await prisma.note.findMany({
      where: {
        userId, // 根据userId筛选笔记
      },
    });
    return NextResponse.json(
      {
        notes,
      },
      { status: 200 }
    );
  } catch (e) {
    console.error("🚀 ~ file: route.ts:30 ~ GET ~ e:", e);
    // 发生错误时返回500状态码和错误信息
    return NextResponse.json(
      {
        message: "获取项目日志失败",
      },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const data = (await request.json()) as NoteRequest;

    const notes = await prisma.note.create({
      data: {
        userId: data.userId,
        avatar: data.avatar,
        content: data.content,
        images: data.images,
        title: data.title,
        date: data.date,
        status: data.status,
        giteeUrl: data.giteeUrl,
      },
    });
    return NextResponse.json(notes, { status: 200 });
  } catch (e) {
    console.error("🚀 ~ file: route.ts:16 ~ POST ~ e:", e);
    return NextResponse.json(
      {
        message: "创建项目日志失败",
      },
      { status: 500 }
    );
  }
}

interface NoteEditRequest {
  id: string; // 确保这个接口包含了你想要更新的字段
  userId: string;
  title: string;
  avatar: string;
  content: string;
  date: string;
  images: string[];
  status: string;
  giteeUrl: string;
}

export async function PUT(request: NextRequest) {
  try {
    // 解析请求体中的数据
    const data = (await request.json()) as NoteEditRequest;
    const { id, ...updateData } = data; // 解构出id和其余需要更新的数据
    // 检查哪些字段为空或缺失
    const missingFields: string[] = [];
    if (!updateData.title) missingFields.push("日志名称");
    if (!updateData.avatar) missingFields.push("头像地址");
    if (!updateData.content) missingFields.push("日志内容");
    if (!updateData.date) missingFields.push("date");
    if (updateData.images.length === 0) missingFields.push("日志图片");
    if (!updateData.status) missingFields.push("更新状态");
    if (!updateData.giteeUrl) missingFields.push("仓库内容");

    if (missingFields.length > 0) {
      // 如果有缺失字段，返回错误信息
      return NextResponse.json(
        { message: `缺少字段: ${missingFields.join(", ")}`, isSucess: 1 },
        { status: 200 }
      );
    }
    // 查找需要更新的笔记
    const noteToUpdate = await prisma.note.findUnique({
      where: {
        id,
      },
    });

    if (!noteToUpdate) {
      // 如果笔记不存在，返回错误
      return NextResponse.json({ message: "日志不存在" }, { status: 404 });
    }

    // 更新笔记
    const updatedNote = await prisma.note.update({
      where: {
        id,
      },
      data: updateData, // 使用解构出的数据来更新笔记
    });

    // 返回更新后的笔记或成功消息
    return NextResponse.json({ isSucess: 0 }, { status: 200 });
  } catch (error) {
    // 处理可能出现的错误
    console.error("Error updating note:" + error);

    // 对于其他错误，返回内部错误消息
    return NextResponse.json({ message: "日志更新异常" }, { status: 500 });
  } finally {
    // 确保在请求结束后关闭PrismaClient
    await prisma.$disconnect();
  }
}
